package com.fy.service;

import com.fy.dao.ProductMapper;
import com.fy.dao.RoundMapper;
import com.fy.entity.Product;
import com.fy.entity.Round;
import com.fy.entity.User;
import com.fy.utils.IdWorker;
import com.fy.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

@Service
public class RoundService {
    @Autowired
    @Qualifier("idWorker2")
    private IdWorker idWorker2;
    @Autowired
    private RoundMapper roundMapper;
    @Autowired
    private ProductMapper productMapper;
    public String publish(Long userId,Long productId, String deposit, String startPrice, String stepPrice, String duration, Date startTime){
        String regex = "^[0-9]+(\\.[0-9]{1,2})?$";
        if(productId == null) return "竞拍商品不能为空!";
        if(deposit == null || !deposit.matches(regex)) return "押金格式错误，请重新输入！";
        if(deposit.equals("0")) return "押金不能为0！";
        if(startPrice == null || !startPrice.matches(regex)) return "起拍价格格式错误，请重新输入!";
        if(startPrice.equals("0")) return "起拍价格不能为0！";
        if(stepPrice == null || !stepPrice.matches(regex)) return "加价幅度格式错误，请重新输入!";
        if(stepPrice.equals("0")) return "加价幅度不能为0！";
        if(Objects.equals(duration,"") || !duration.matches(regex)) return "竞拍天数格式错误，请重新输入!";
        if(duration.equals("0")) return "竞拍天数不能为0！";
        if(startTime == null) return "开始时间不能为空!";
        if(startTime.before(new Date())) return "开始时间应该晚于当前时间！请重新选择！";

        //--将字符串转换成BigDecimal类型
        BigDecimal deposit1 = new BigDecimal(deposit);
        BigDecimal startPrice1 = new BigDecimal(startPrice);
        BigDecimal stepPrice1 = new BigDecimal(stepPrice);
        synchronized(this) {
            Round round = new Round();
            round.setId(idWorker2.nextId());
            round.setProductid(productId);
            round.setSalerid(userId);
            round.setDeposit(deposit1);
            round.setStartprice(startPrice1);
            round.setStepprice(stepPrice1);
            round.setDuration(duration);
            round.setStarttime(startTime);
            round.setState("1");
            round.setCallamount(0);
            roundMapper.insert(round);

            //--修改product表中的商品状态
            modifyStateById(productId,1);
        }
        return "恭喜您发布成功!!!";
    }
    //--id state
    public int modifyStateById(Long productId,Integer state){
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setUpdatetime(new Date());
        product.setState(state);
        return productMapper.updateByPrimaryKey(product);
    }
}
